package com.cee.admin.config.interceptor;

import com.cee.common.core.context.FileCleanContext;
import com.cee.common.utils.CollectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.http.HttpMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 文件清理拦截器
 * @author wsz
 * @since 2023/9/13
 */
@Slf4j
public class FileCleanContextInterceptor implements HandlerInterceptor, ApplicationListener<ContextClosedEvent> {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (isMatchedRequestMethod(request.getMethod())) {
            FileCleanContext.initFileDeletedTask();
        }
        return true;
    }

    private boolean isMatchedRequestMethod(String method) {
        return !HttpMethod.OPTIONS.matches(method);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        if (isMatchedRequestMethod(request.getMethod())) {
            try {
                FileCleanContext.asyncStartClean();
            } finally {
                FileCleanContext.remove();
            }
        }
    }

    @Override
    public void onApplicationEvent(ContextClosedEvent event) {
        Map<Long, Set<String>> allDeleteFileMap = FileCleanContext.getAllDeleteFileMap();
        if (CollectionUtils.isEmpty(allDeleteFileMap)) {
            return;
        }
        Collection<Set<String>> values = allDeleteFileMap.values();
        if (CollectionUtils.isNotEmpty(values)) {
            Set<String> unDeleteFileSet = new HashSet<>();
            for (Set<String> value : values) {
                if (CollectionUtils.isNotEmpty(value)) {
                    unDeleteFileSet.addAll(value);
                }
            }
            if (!CollectionUtils.isEmpty(unDeleteFileSet)) {
                log.error("以下待删除文件可能没有被删除：{}", values);
            }
        }
    }
}
